<?php
/**
 * Description: 获取用户的邀请码使用信息
 * User: devforma
 * Date: 16/3/1
 * Time: 17:36
 */

class GetUserInvites implements iController {
    private $now;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb, $uddb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $this->now = time();
        if ($this->checkInviteCode($queryArgs['user_id'])) {
            $inviteCode = dechex($queryArgs['user_id']);
        } else {
            $inviteCode = '无';
        }

        $allInvites = $cmsdb->getResults('SELECT i.id, i.user_id, i.order_time, i.cashback_fee, i.status, c.course_name, c.refund_deadline
FROM `order_invites` AS i INNER JOIN `data_live_course` AS c ON i.course_id=c.id AND i.invite_user_id=:uid ORDER BY i.id DESC',
            array(':uid' => $queryArgs['user_id']));

        $list = array();
        $fee = 0;
        if (!empty($allInvites)) {
            $users = array();
            foreach ($allInvites as $i) {
                $users[] = $i->user_id;
            }
            $users = $this->getUsers($users);

            foreach ($allInvites as $invite) {
                $status = $this->getInviteStatus($invite->id, $invite->status, $invite->refund_deadline);

                if ($status == 'done') {
                    $fee += $invite->cashback_fee;
                }

                $list[] = array(
                    'avatar' => self::getAvatarUrl($users[$invite->user_id]->avatar),
                    'nickname' => $users[$invite->user_id]->nickname,
                    'course_name' => $invite->course_name,
                    'order_time' => explode(' ', $invite->order_time)[0],
                    'cashback_fee' => intval($invite->cashback_fee),
                    'status' => $status
                );
            }
        }

        //获取用户提现记录
        $withdraw = $this->getWithdrawInfo($queryArgs['user_id']);

        //计算剩余可提现金额
        $fee -= $withdraw['total_fee'];

        //更新用户的可提现金额
        $uddb->update('user_social_info', array('cashback_fee' => $fee),
            array('user_id' => $queryArgs['user_id']));


        $alipayInfo = $this->getAlipayInfo($queryArgs['user_id']);

        return genOutput(1, array(
            'alipay_account' => (string)$alipayInfo->alipay_id,
            'alipay_name' => (string)$alipayInfo->alipay_name,
            'invite_code' => $inviteCode,
            'total_fee' => $fee,
            'invite_list' => $list,
            'cashback_list' => $withdraw['list']
        ));
    }


    /**
     * 获取用户的支付宝信息
     *
     * @param $userId
     * @return mixed
     */
    private function getAlipayInfo($userId) {
        global $uddb;

        $info = $uddb->getRow('SELECT `alipay_id`, `alipay_name` FROM `user_social_info` WHERE `user_id`=:uid',
            array(':uid' => $userId));

        return $info;
    }


    /**
     * 获取提现信息
     *
     * @param $userId
     * @return array
     */
    private function getWithdrawInfo($userId) {
        global $cmsdb;

        $results = $cmsdb->getResults('SELECT * FROM `withdraw_records` WHERE `user_id`=:uid ORDER BY `id` DESC',
            array(':uid' => $userId));

        $list = array();
        $totalFee = 0;
        foreach ($results as $r) {
            if ($r->status == 0) {
                $status = 'fail';
            } elseif ($r->status == 1) {
                $status = 'success';
                $totalFee += $r->total_fee;
            } else {
                $status = 'process';
                $totalFee += $r->total_fee;
            }

            $list[] = array(
                'refund_time' => explode(' ', $r->create_time)[0],
                'refund_fee' => intval($r->total_fee),
                'status' => $status
            );
        }

        return array(
            'list' => $list,
            'total_fee' => $totalFee
        );
    }


    /**
     * 处理头像地址
     *
     * @param $url
     * @return string
     */
    static function getAvatarUrl($url) {
        if (!empty($url) && strpos($url, 'http://') === false) {
            $url = 'http://edu.appublisher.com/user-images/avatar/'.$url;
        }

        return $url;
    }


    /**
     * 获取用户信息列表
     *
     * @param $users
     * @return array
     */
    private function getUsers($users) {
        global $uddb;

        $string = implode(',', $users);

        $users = $uddb->getResults("SELECT `user_id`, `nickname`, `avatar` FROM `user_social_info` WHERE `user_id` IN ({$string})");

        $list = array();
        foreach ($users as $u) {
            $list[$u->user_id] = $u;
        }

        return $list;
    }


    /**
     * 获取邀请码使用记录状态
     *
     * @param $inviteId
     * @param $inviteStatus
     * @param $refundDeadline
     * @return string
     */
    private function getInviteStatus($inviteId, $inviteStatus, $refundDeadline) {
        global $cmsdb;

        if ($inviteStatus == 2) {
            if (empty($refundDeadline) || strtotime($refundDeadline) <= $this->now) {
                $status = 'done';

                //更新记录为已完成(解冻)
                $cmsdb->update('order_invites', array('status' => 1), array('id' => $inviteId));
            } else {
                $status = 'freeze';
            }
        } elseif ($inviteStatus == 1) {
            $status = 'done';
        } else {
            $status = 'refund';
        }

        return $status;
    }

    /**
     * 检测是否有邀请码
     *
     * @param $userId
     * @return bool
     */
    private function checkInviteCode($userId) {
        global $cmsdb;
        $courseIds = $cmsdb->getCol('SELECT `id` FROM `data_live_course` WHERE `can_invite`=1');
        $idsStr = implode(',', $courseIds);

        $exists = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id` IN ('.
            $idsStr.') AND `product_type`="zhiboke" LIMIT 1', array(':uid' => $userId));

        return !empty($exists);
    }
}